package com.car.util;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.InputStream;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;

public class BitmapUtil {

	public static Bitmap decodeSampledBitmap(FileDescriptor fileDescriptor,
			int reqWidth, int reqHeight) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
		System.out.println("start" + options.inSampleSize);
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		System.out.println("after" + options.inSampleSize);
		options.inJustDecodeBounds = false;
		return BitmapFactory
				.decodeFileDescriptor(fileDescriptor, null, options);
	}

	private static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {

		final int height = options.outHeight;
		final int width = options.outWidth;

		int inSampleSize = 1;

		if (height != 0 && width != 0) {
			if (height > reqHeight || width > reqWidth) {
				final int heightRatio = Math.round((float) height
						/ (float) reqHeight);
				final int widthRatio = Math.round((float) width
						/ (float) reqWidth);

				inSampleSize = heightRatio < widthRatio ? heightRatio
						: widthRatio;
			}
		}
		// System.out.println(inSampleSize);
		return inSampleSize;
	}

	public static Bitmap decodeSampledBitmap(InputStream inputStream,
			int reqWidth, int reqHeight) throws FileNotFoundException {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(inputStream, null, options);
		options.inSampleSize = calculateInSampleSize(options, reqHeight,
				reqWidth);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeStream(inputStream, null, options);

	}

	public static Bitmap decodeSampledBitmap(Resources resources, int resId,
			int reqWidth, int reqHeight) throws FileNotFoundException {
		return null;
	}

}
